﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Caching;
using System.Text;
using System.Threading.Tasks;

namespace WebLib
{
    public enum CacheHelperPriority
    {
        Default,
        NotRemovable
    }

    public class CacheHelper<T>
    {
        private static ObjectCache cache = MemoryCache.Default;
        private CacheItemPolicy _policy;
        private CacheEntryRemovedCallback _callback;

        public void AddToCache(string cacheKeyName, T cacheItem, CacheHelperPriority myCacheItemPriority)
        {
            _callback = CachedItemRemovedCallback;
            _policy = new CacheItemPolicy
            {
                Priority = (myCacheItemPriority == CacheHelperPriority.Default)
                    ? CacheItemPriority.Default
                    : CacheItemPriority.NotRemovable,
                AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(10),
                RemovedCallback = _callback
            };
            //_policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePath));

            cache.Set(cacheKeyName, cacheItem, _policy); 
        }

        public T GetCachedItem(string cacheKeyName)
        {
            if (cache[cacheKeyName] is T)
                return (T) cache[cacheKeyName];
            
            return default(T);
        }

        public void RemoveCachedItem(string cacheKeyName)
        {
            if (cache.Contains(cacheKeyName))
            {
                cache.Remove(cacheKeyName);
            }
        }

        private void CachedItemRemovedCallback(CacheEntryRemovedArguments arguments) 
        { 
            // Log these values from arguments list 
            var strLog = String.Concat("Reason: ", arguments.RemovedReason.ToString(), " | Key-Name: ", arguments.CacheItem.Key, " | Value-Object: ", arguments.CacheItem.Value.ToString()); 
        }
    }
}
